<?php

if (is_numeric($_POST['ref_id']) and is_numeric($_POST['id'])) {
	// both ids are numeric
	if ($db->fetchOne("SELECT id FROM site_pages WHERE site_id=? AND id=?", array($site['id'], $_POST['ref_id'])) and $db->fetchOne("SELECT id FROM site_pages WHERE site_id=? AND id=?", array($site['id'], $_POST['id']))) {
		// both ids belong to this site
		$logger->debug($_POST['type']);
		if ($_POST['type'] == 'inside') {
			$sort = $db->fetchOne("SELECT MAX(sort)+10 FROM site_pages WHERE parent_id=?", $_POST['ref_id']);
			$db->update('site_pages', array('parent_id' => $_POST['ref_id'], 'sort' => $sort), $db->quoteInto("id=?", $_POST['id']));
		} else {
			list($parent_id, $sort) = array_values($db->fetchRow("SELECT parent_id, sort FROM site_pages WHERE id=?", $_POST['ref_id']));
			$sort = $_POST['type'] == 'after' ? $sort+5 : $sort-5;
			$db->update('site_pages', array('parent_id' => $parent_id, 'sort' => $sort), $db->quoteInto("id=?", $_POST['id']));
			// reassign sort x 10
			$page_ids = $db->fetchCol("SELECT id FROM site_pages WHERE parent_id=? ORDER BY sort", $parent_id);
			for($i=0;$i<count($page_ids);$i++) {
				$db->update('site_pages', array('sort' => $i*10+10), "id={$page_ids[$i]}");
			}
		}
		header('Content-type: application/json');
		echo json_encode(array('id' => $_POST['id']));
		
	}
	
}
